package com.xindaoapp.framework.activity;

import java.util.List;

import org.apache.http.Header;
import org.apache.http.cookie.Cookie;

import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.xindaoapp.framework.MainActivity;
import com.xindaoapp.framework.R;
import com.xindaoapp.framework.api.AddClient;
import com.xindaoapp.framework.api.Address;
import com.xindaoapp.framework.api.ConstantsValue;
import com.xindaoapp.framework.base.BaseActivity;
import com.xindaoapp.framework.bean.UserInfo;
import com.xindaoapp.framework.utils.CommonUtil;
import com.xindaoapp.framework.utils.CustomToast;
import com.xindaoapp.framework.utils.ProgressHUD;

/**
 * ============================================================
 * 
 * 版权 : 新道APP (c) 2014
 * 
 * 作者 : 贺奕凯
 * 
 * 版本 : 1.0
 * 
 * 创建日期 : 2014-6-24 下午4:19:57
 * 
 * 描述 : 注册界面
 * 
 * 修订历史 ：
 * 
 * ============================================================
 **/
public class RegisterActivity extends BaseActivity implements OnClickListener {
	protected static final int REGISTER_OK = 2;
	protected static final int LOGIN_OK = 20;
	@ViewInject(R.id.tittle_common_cancel)
	private ImageView tittle_common_cancel;
	@ViewInject(R.id.tittle_common_content)
	private TextView tittle_common_content;

	@ViewInject(R.id.register_username)
	private EditText register_username;
	@ViewInject(R.id.register_paw1)
	private EditText register_paw1;
	@ViewInject(R.id.register_paw2)
	private EditText register_paw2;
	@ViewInject(R.id.register_mail)
	private EditText register_mail;
	@ViewInject(R.id.register)
	private Button register;
	@ViewInject(R.id.xieyi)
	private CheckBox xieyi;

	private String username;
	private String password1;
	private String password2;
	private String email;

	private final Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case REGISTER_OK:
				login(username, password1);
				if(ConstantsValue.loginByQQ){
					bindQQ(username,password1);
				}
				if(ConstantsValue.loginBySina){
					bindSina(username,password1);
				}
				break;
			case LOGIN_OK:
				finish();
				break;
			default:
				break;
			}
		}

	};
	private SharedPreferences sp;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_register);
		ViewUtils.inject(this);
		sp = getSharedPreferences("userconfig", MODE_PRIVATE);
		setListener();
	}

	protected void openLoginActivity() {
		Intent intent = new Intent(this, LoginActivity.class);
		startActivity(intent);
		finish();
	}

	private void setListener() {
		tittle_common_content.setText("注册");
		register.setOnClickListener(this);
		tittle_common_cancel.setOnClickListener(this);
		xieyi.setChecked(true);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.register:
			username = register_username.getText().toString().trim();
			password1 = register_paw1.getText().toString().trim();
			password2 = register_paw2.getText().toString().trim();
			email = register_mail.getText().toString().trim();
			if (checkUserName() && checkPassWord() && checkEmail() && checkXieYi()) {
				register(username, password1, email);
			}
			break;
		case R.id.tittle_common_cancel:
			finish();
			break;
		default:
			break;
		}
	}

	private boolean checkEmail() {
		if (TextUtils.isEmpty(email)) {
			Toast.makeText(getApplicationContext(), "邮箱不能为空", Toast.LENGTH_SHORT).show();
			return false;
		}
		if (!email
				.matches("^([a-z0-9A-Z]+[-|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$")) {
			Toast.makeText(getApplicationContext(), "邮箱地址错误", Toast.LENGTH_SHORT).show();
			return false;
		}
		return true;
	}

	private boolean checkPassWord() {
		if (TextUtils.isEmpty(password1) || TextUtils.isEmpty(password2)) {
			Toast.makeText(getApplicationContext(), "密码不能为空", Toast.LENGTH_SHORT).show();
			return false;
		}
		if (!password1.equals(password2)) {
			Toast.makeText(getApplicationContext(), "密码不一致", Toast.LENGTH_SHORT).show();
			return false;
		}
		if (!password1.matches("^[0-9a-zA-Z]{6,22}$")) {
			Toast.makeText(getApplicationContext(), "请输入正确的密码", Toast.LENGTH_SHORT).show();
			return false;
		}
		return true;
	}

	private boolean checkUserName() {
		if (TextUtils.isEmpty(username)) {
			Toast.makeText(getApplicationContext(), "请输入用户名", Toast.LENGTH_SHORT).show();
			return false;
		}
		return true;
	}

	private boolean checkXieYi() {
		if (!xieyi.isChecked()) {
			showToast("请阅读并同意乐宠协议");
			return false;
		}
		return true;
	}

	public void openMainActivity() {
		Intent intent = new Intent(this, MainActivity.class);
		startActivity(intent);
	}

	private void register(final String name, final String psw, String email) {

		RequestParams params = new RequestParams();
		params.put("username", name);
		params.put("password", psw);
		params.put("email", email);
		final ProgressHUD ProgressDialog = ProgressHUD.show(this, "正在加载...", true, true, null);
		AddClient.post(Address.REGISTER, params, new AsyncHttpResponseHandler() {
			@Override
			public void onSuccess(int statusCode, String content) {
				if (null != ProgressDialog && ProgressDialog.isShowing()) {
					ProgressDialog.dismiss();
				}
				UserInfo userinfo = JSON.parseObject(content, UserInfo.class);
				if (userinfo.getResult().equals("-1")) {
					showToast(userinfo.getMsg());
					return;
				} else {
					ConstantsValue.uid = userinfo.getUserinfo().uid;
					ConstantsValue.setUser(userinfo.getUserinfo());
					ConstantsValue.isLogin = true;
					showToast("注册成功");
					ConstantsValue.REGISTERNAME = name;
					ConstantsValue.REGISTERPSW = psw;
					handler.sendEmptyMessage(REGISTER_OK);
				}
				super.onSuccess(statusCode, content);
			}

			@Override
			public void onFailure(Throwable error, String content) {
				if (null != ProgressDialog && ProgressDialog.isShowing()) {
					ProgressDialog.dismiss();
				}

				super.onFailure(error, content);
			}
		});
	}

	public void showToast(String msg) {
		showToast(msg, 0);
	}

	public void showToast(String msg, int time) {
		CustomToast customToast = new CustomToast(this, msg, time);
		customToast.show();
	}

	@Override
	protected void onPause() {
		finish();
		super.onPause();
	}

	private void login(final String name, final String psw) {
		if (0 == CommonUtil.isNetworkAvailable(this)) {
			showToast("请检查网络状态");
		} else {
			RequestParams params = new RequestParams();
			params.put("username", name);
			params.put("password", psw);
			final ProgressHUD ProgressDialog = ProgressHUD.show(this, "正在加载...", true, true, null);
			AddClient.post(Address.LOGIN, params, new AsyncHttpResponseHandler() {
				public void onSuccess(int statusCode, Header[] headers, String content) {
					if (null != ProgressDialog && ProgressDialog.isShowing()) {
						ProgressDialog.dismiss();
					}
					UserInfo userinfo = JSON.parseObject(content, UserInfo.class);;
					if (userinfo.getResult().equals("-1")) {
						showToast(userinfo.getMsg());
						return;
					} else {
						ConstantsValue.uid = userinfo.getUserinfo().uid;
						ConstantsValue.setUser(userinfo.getUserinfo());
						ConstantsValue.isLogin = true;
						Editor edit = sp.edit();
						edit.putString("username", name);
						edit.putString("password", psw);
						edit.commit();
						handler.sendEmptyMessage(LOGIN_OK);
					}
					ConstantsValue.cookieStore = AddClient.getClient().getCookie();
					List<Cookie> cookies = ConstantsValue.cookieStore.getCookies();
					super.onSuccess(statusCode, headers, content);
				}
				@Override
				public void onFailure(Throwable error, String content) {
					if (null != ProgressDialog && ProgressDialog.isShowing()) {
						ProgressDialog.dismiss();
					}
					showToast("登录失败,请重试");
					super.onFailure(error, content);
				}
			});
		}
	}
	private void bindQQ(String username2, String password2) {
		RequestParams params = new RequestParams();
		params.put("username", username2);
		params.put("password", password2);
		params.put("conuin", "");
		params.put("conuinsecret", "");
		params.put("conopenid", ConstantsValue.info.openid);
		final ProgressHUD ProgressDialog = ProgressHUD.show(this, "正在加载...", true, true, null);
		AddClient.get(Address.BINDQQ, params, new AsyncHttpResponseHandler() {
			@Override
			public void onSuccess(int statusCode, String content) {
				if (null != ProgressDialog && ProgressDialog.isShowing()) {
					ProgressDialog.dismiss();
				}
				UserInfo userinfo = JSON.parseObject(content, UserInfo.class);
				if(userinfo.getResult().equals("0")){
					Toast.makeText(getApplicationContext(), "绑定QQ成功", Toast.LENGTH_SHORT).show();
					ConstantsValue.uid = userinfo.getUserinfo().uid;
					ConstantsValue.setUser(userinfo.getUserinfo());
					ConstantsValue.isLogin = true;
					ConstantsValue.loginByQQ = true;
					Editor edit = sp.edit();
					edit.putString("username", username);
					edit.putString("password", "");
					edit.commit();
					finish();
				}else{
					Toast.makeText(getApplicationContext(),userinfo.getMsg() , Toast.LENGTH_SHORT).show();
				}
				super.onSuccess(statusCode, content);
			}

			@Override
			public void onFailure(Throwable error, String content) {
				if (null != ProgressDialog && ProgressDialog.isShowing()) {
					ProgressDialog.dismiss();
				}
				super.onFailure(error, content);
			}
		});
	}
	private void bindSina(String username2, String password2) {
		RequestParams params = new RequestParams();
		params.put("sina_uid", ConstantsValue.sina.getString("uid"));
		params.put("token", ConstantsValue.sina.getString("access_token"));
		params.put("oauth2_expiretime", ConstantsValue.sina.getString("expires_in")+"");
		params.put("username", username2);
		params.put("password", password2);
		final ProgressHUD ProgressDialog = ProgressHUD.show(this, "正在加载...", true, true, null);
		AddClient.get(Address.BINDSINA, params, new AsyncHttpResponseHandler() {
			@Override
			public void onSuccess(int statusCode, String content) {
				if (null != ProgressDialog && ProgressDialog.isShowing()) {
					ProgressDialog.dismiss();
				}
				UserInfo userinfo = JSON.parseObject(content, UserInfo.class);
				if (userinfo.getResult().equals("0")) {
					ConstantsValue.uid = userinfo.getUserinfo().uid;
					ConstantsValue.setUser(userinfo.getUserinfo());
					ConstantsValue.isLogin = true;
					Editor edit = sp.edit();
					edit.putString("username", userinfo.userinfo.username);
					edit.putString("password", "");
					edit.commit();
					handler.sendEmptyMessage(LOGIN_OK);
					Toast.makeText(getApplicationContext(),"绑定微博成功", Toast.LENGTH_SHORT).show();
				}else{
					Toast.makeText(getApplicationContext(), userinfo.getMsg(), Toast.LENGTH_SHORT).show();
				}
				super.onSuccess(statusCode, content);
			}

			@Override
			public void onFailure(Throwable error, String content) {
				if (null != ProgressDialog && ProgressDialog.isShowing()) {
					ProgressDialog.dismiss();
				}
				super.onFailure(error, content);
			}
		});
	}
}
